﻿using System.Data.SqlClient;
using NAnt.Core.Attributes;

namespace ECM7.NantContrib.Tasks.SqlServer
{
	[TaskName("createDatabase")]
	public class CreateDatabaseTask : BaseSqlServerTask
	{
		[TaskAttribute("errorIfAlreadyExists", Required = false), BooleanValidator]
		public bool ErrorIfAlreadyExists { get; set; }

		/// <summary>
		/// Выполнение необходимых действий
		/// </summary>
		protected override void ExecuteTask()
		{
			SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
			{
				DataSource = Instance,
				UserID = User ?? string.Empty,
				Password = Password ?? string.Empty,
				IntegratedSecurity = IntegratedSecurity
			};

			using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
			{
				string sql = ErrorIfAlreadyExists 
					? "CREATE DATABASE [{0}]"
					: "IF (NOT EXISTS (SELECT name FROM sys.databases WHERE name = @db)) CREATE DATABASE [{0}]";

				connection.Open();
				using (SqlCommand command = connection.CreateCommand())
				{
					command.CommandText = string.Format(sql, Database);
					command.Parameters.AddWithValue("@db", Database);

					ExecuteCommand(command);
				}
			}
		}
	}
}
